package getDataFromAciveMQ;

import java.util.ArrayList;
import java.util.List;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQQueue;
import org.json.JSONObject;

import pojo.Book;
import util.ActiveMqUtil;
import dao.impl.BookDaoImpl;

public class GetDataFromAciveMQ {
	public static void main(String[] args) throws JMSException {
		final BookDaoImpl impl = new BookDaoImpl();
		Destination queue = new ActiveMQQueue("matthew");
		Connection con = ActiveMqUtil.createConnection();
		con.start();
		
		Session sen = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		final MessageConsumer consumer = sen.createConsumer(queue);
		
		new Thread(){
			@Override
			public void run() {
				JSONObject json = null;
				String jsonString = null;
				List<Book> books = new ArrayList<Book>();
				int i = 1;
				try {
					while(i++ <= 10000){
						TextMessage msg = (TextMessage) consumer.receive();
						jsonString = msg.getText();
						Book book = impl.transferJsonToBook(jsonString);
						books.add(book);
						
						if(books.size() % 500 == 0){
							impl.addBookList(books);
							books.clear();
						}
					}
					
					impl.addBookList(books);
					
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}.start();
		
//		consumer.close();
//		sen.close();
//		con.close();
	}
}
